//
//  KernelParameterVC.m
//  RTUApp
//
//  Created by 陈德军 on 2017/7/3.
//  Copyright © 2017年 陈德军. All rights reserved.
//

#import "KernelParameterVC.h"
#import "EssentialParameterTableViewCell.h"
#import "SearchEquipment2TableViewCell.h"



@interface KernelParameterVC ()<UITableViewDelegate,UITableViewDataSource,YZNavigationMenuViewDelegate,EssentialParameterTableViewCellDelegate>{
    NSString *str6;
    NSString *dataStr;
    //修改前的数据
    NSString *originalStr;
}
/**
 *  tableview
 */
@property (nonatomic,strong) UITableView *tableV;
/**
 *  数据数组
 */
@property (nonatomic,strong) NSMutableArray<SearchEquipmentModel *> *dataSoucer;
/**
 *  菜单
 */
@property (nonatomic,strong) YZNavigationMenuView *menuView;
@end

@implementation KernelParameterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = KK_MailColor;
    self.tableV = [[UITableView alloc] init];
    self.tableV.size = CGSizeMake(kScreenWidth, kScreenHeight-64);
    self.tableV.top = 0;
    self.tableV.left = 0;
    [self.tableV registerClass:[EssentialParameterTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableV registerClass:[SearchEquipment2TableViewCell class] forCellReuseIdentifier:@"cell2"];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightBarButtonItemClicked)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.dataSoucer = [NSMutableArray new];
    
    kHMBlueToothManager.failureBlock = ^(NSString *value) {
        [self.dataSoucer removeAllObjects];
        [self refreshData:originalStr];
        [self.tableV reloadData];
    };
    kHMBlueToothManager.bluetoothConnectionDisconnect = ^(NSString *value) {
        self.navigationController.navigationBar.barTintColor = KK_MailColor;
        self.navigationItem.title = @"蓝牙连接断开";
        [PopupView showMessageStr:@"蓝牙连接断开"];
    };
    [self getData];
}

- (void)getData{
    NSData *data = [self stringToByte:@"68020009017416"];
    [kHMBlueToothManager sendData:data];
    [LoaddingViewDJ show];
    kHMBlueToothManager.dataBlock = ^(NSData *value) {
        if (![self.dataSoucer isKindOfClass:[NSArray class]]) return ;
        if (self.dataSoucer.firstObject) {
            return ;
        }
        NSMutableString *str1 = [NSMutableString stringWithFormat:@"%@",value];
        //第一个参数是要删除的字符的索引，第二个是从此位开始要删除的位数
        [str1 deleteCharactersInRange:NSMakeRange(0, 1)];
        [str1 deleteCharactersInRange:NSMakeRange(str1.length-1, 1)];
        //删除字符串中的空格
        NSString *str4 = [str1 stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString *str2 = [str4 substringToIndex:2];
        NSString *str3 = [str4 substringFromIndex:str4.length-2];
        
        if ([str2 isEqualToString:@"68"] && [str3 isEqualToString:@"16"]) {
            str6 = str4;
            str6 = [NSString stringWithFormat:@"%@%@",str6,str4];
            originalStr = str6;
            NSLog(@"最后一行%@",str6);
            [self refreshData:str6];
            [self.tableV reloadData];
        }else if ([str2 isEqualToString:@"68"]){
            str6 = str4;
        }else if (![str3 isEqualToString:@"16"]){
            str6 = [NSString stringWithFormat:@"%@%@",str6,str4];
        }else{
            
        }
    };
}

- (void)refreshData:(NSString *)data{
    [self stringFromHexString:data];
    if (![[data substringToIndex:6] isEqualToString:@"680900"] ) {
        return ;
    }
    [LoaddingViewDJ dismiss];
    dataStr = str6;
    SearchEquipmentModel *model = [SearchEquipmentModel new];
    model.num = @"ID";
    model.name = @"名称";
    model.macID = @"数据";
    model.butTitle = @"备注";
    [self.dataSoucer addObject:model];
    
    NSMutableString *str7 = [NSMutableString stringWithFormat:@"%@",data];
    if (str7.length<11) {
        return;
    }
    
    {
        [str7 deleteCharactersInRange:NSMakeRange(0, 10)];
        SearchEquipmentModel *model1 = [SearchEquipmentModel new];
        model1.num = @"0xc8";
        [str7 deleteCharactersInRange:NSMakeRange(0, 4)];
        model1.name = @"密码";
        NSData *B1data = [self stringToByte:[str7 substringToIndex:4]];
        uint16_t B1y = *(uint16_t*)B1data.bytes;
        model1.macID = [NSString stringWithFormat:@"%.1hu",B1y];
        [str7 deleteCharactersInRange:NSMakeRange(0, 4)];
        model1.butTitle = @"密码";
        [self.dataSoucer addObject:model1];
    }
    {
        [str7 deleteCharactersInRange:NSMakeRange(0, 4)];
        SearchEquipmentModel *model1 = [SearchEquipmentModel new];
        model1.num = @"0xc9";
        model1.name = @"站名称";
        NSLog(@"%@",[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%lu",strtoul([[str7 substringToIndex:2] UTF8String],0,16)]]);
        model1.macID = [self kernelName:[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%lu",strtoul([[str7 substringToIndex:2] UTF8String],0,16)]]];
        [str7 deleteCharactersInRange:NSMakeRange(0, 2)];
        model1.butTitle = @"站名称";
        [self.dataSoucer addObject:model1];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)rightBarButtonItemClicked
{
    
    self.menuView.delegate = self;
    [self.tableV addSubview:self.menuView];
}


#pragma mark - SearchEquipmentTableViewCellDelegate 代理分组
- (void)didClickTextField:(NSString *)Text andID:(NSString *)ID andName:(NSString *)name{
    NSMutableString *sendStr = [NSMutableString stringWithFormat:@"%@",[dataStr substringToIndex:24]];
    [sendStr replaceCharactersInRange:NSMakeRange(9, 1) withString:@"2"];
    
    if ([name isEqualToString:@"密码"]) {
        uint16_t y = [Text intValue] + 1;
        NSData *data7 = [NSData dataWithBytes:&y length:sizeof(y)];
        NSMutableString *newStr = [NSMutableString stringWithFormat:@"%@",data7];
        //第一个参数是要删除的字符的索引，第二个是从此位开始要删除的位数
        [newStr deleteCharactersInRange:NSMakeRange(0, 1)];
        [newStr deleteCharactersInRange:NSMakeRange(newStr.length-1, 1)];
        //删除字符串中的空格
        NSString *str4 = [newStr stringByReplacingOccurrencesOfString:@" " withString:@""];
        [sendStr replaceCharactersInRange:NSMakeRange(14, 4) withString:str4];
        NSString *checksum = [self getAddtion:[self hexToByteArr:sendStr]];
        sendStr = [NSMutableString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@%@16",sendStr,checksum]];
        dataStr = sendStr;
    }
}

#pragma mark - YZNavigationMenuViewDelegate 代理分组
- (void)navigationMenuView:(YZNavigationMenuView *)menuView clickedAtIndex:(NSInteger)index;
{
    switch (index) {
        case 0:{
            NSLog(@"请选着");
        }
            break;
        case 1:{
            NSLog(@"设置");
            NSData *data = [self stringToByte:dataStr];
            [kHMBlueToothManager sendMsgWithSubPackage:data];
        }
            break;
        case 2:{
            [self getData];
        }
            break;
        case 3:{
            NSLog(@"默认值");
            NSMutableString *datastr = [[NSUserDefaults standardUserDefaults] objectForKey:@"KernelParameterVC"];
            if (datastr.length>10) {
                [self refreshData:datastr];
                [self.tableV reloadData];
            }else{
                [PopupView showMessageStr:@"没有默认值,请先设置!"];
            }
            
        }
            break;
        case 4:{
            NSLog(@"保存为默认");
            [[NSUserDefaults standardUserDefaults] setObject:dataStr forKey:@"KernelParameterVC"];
            [PopupView showMessageStr:@"设置成功"];
        }
            break;
        default:
            break;
    }
}

#pragma mark - UITableViewDelegate 代理分组
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSoucer.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        SearchEquipment2TableViewCell *cell = [SearchEquipment2TableViewCell cellWithtableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setModel:self.dataSoucer[indexPath.row]];
        return cell;
    }else{
        EssentialParameterTableViewCell *cell = [EssentialParameterTableViewCell cellWithtableView:tableView];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setModel:self.dataSoucer[indexPath.row]];
        if (indexPath.row == 0) {
            cell.orderNumberLabel.textColor = KK_MailColor;
            cell.equipmentNameLabel.textColor = KK_MailColor;
            cell.macIDLabel.textColor = KK_MailColor;
            cell.connectBut.textColor = KK_MailColor;
        }else{
            cell.orderNumberLabel.textColor = [UIColor blackColor];
            cell.equipmentNameLabel.textColor = [UIColor blackColor];
            cell.macIDLabel.textColor = [UIColor blackColor];
            cell.connectBut.textColor = [UIColor blackColor];
        }
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        AlertViewDJ *aler = [AlertViewDJ new];
        NSArray *dataArr = @[@"降水",@"河道",@"水库",@"闸坝",@"泵站",@"潮汐",@"墒情",@"地下水",@"水质",@"取水口",@"排水口"];
        aler.dataBlock = ^(NSString *value) {
            self.dataSoucer[2].macID = [self kernelName:[NSString stringWithFormat:@"%d",[value intValue]-1]];
            [self.tableV reloadData];
            NSMutableString *sendStr = [NSMutableString stringWithFormat:@"%@",[dataStr substringToIndex:24]];
            [sendStr replaceCharactersInRange:NSMakeRange(9, 1) withString:@"2"];
            NSMutableString *str1 = [NSMutableString new];  //替换字符串
            str1 = [NSMutableString stringWithFormat:@"%@",[self inFrontOfTheFill:[[NSString alloc] initWithFormat:@"%1x",[value intValue]-1]]];
            [sendStr replaceCharactersInRange:NSMakeRange(22, 2) withString:str1];
            NSString *checksum = [self inFrontOfTheFill:[self getAddtion:[self hexToByteArr:sendStr]]];
            sendStr = [NSMutableString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@%@16",sendStr,checksum]];
            dataStr = sendStr;
        };
        [aler setlist:dataArr];
        [aler show];
    }
    
}

#pragma mark - 懒加载
- (YZNavigationMenuView *)menuView{
    if (!_menuView) {
        _menuView = [[YZNavigationMenuView alloc] initWithPositionOfDirection:CGPointMake(self.view.frame.size.width - 24, 5) images:nil titleArray:@[@"请选择",@"设置",@"读取",@"默认值",@"保存为默认"]];
    }
    
    return _menuView;
    
}




#pragma mark - 转换工具
- (NSString *)kernelName:(NSString *)str{
    NSString *returnStr = [NSString new];
    switch ([str intValue]) {
        case 0:
            returnStr = @"降水";
            break;
        case 1:
            returnStr = @"河道";
            break;
        case 2:
            returnStr = @"水库";
            break;
        case 3:
            returnStr = @"闸坝";
            break;
        case 4:
            returnStr = @"泵站";
            break;
        case 5:
            returnStr = @"潮汐";
            break;
        case 6:
            returnStr = @"墒情";
            break;
        case 7:
            returnStr = @"地下水";
            break;
        case 8:
            returnStr = @"水质";
            break;
        case 9:
            returnStr = @"取水口";
            break;
        case 10:
            returnStr = @"排水口";
            break;
            
        default:
            break;
    }
    
    return returnStr;
}


-(NSData*)stringToByte:(NSString*)string
{
    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"%lu",(unsigned long)[hexString length]);
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}

-(NSString *)stringFromHexString:(NSString *)hexString { //
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    //    NSLog(@"------字符串------%@",unicodeString);
    return unicodeString;
}
//把 byte数组转成 Int类型的数据
-(int) lBytesToInt:(NSString *)string
{
    NSString *str1 = [NSString stringWithFormat:@"%lu",strtoul([[string substringToIndex:2] UTF8String],0,16)];
    NSString *str2 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(2, 2)] UTF8String],0,16)];
    NSString *str3 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(4, 2)] UTF8String],0,16)];
    
    int  temp1 = [str1 intValue];
    int  temp2 = [str2 intValue];
    int  temp3 = [str3 intValue];
    Byte byte1[] = {temp1,temp2,temp3};
    
    int height = 0;
    NSData * testData =[NSData dataWithBytes:byte1 length:4];
    for (int i = 0; i < [testData length]; i++)
    {
        if (byte1[[testData length]-i] >= 0)
        {
            height = height + byte1[[testData length]-i];
        } else
        {
            height = height + 256 + byte1[[testData length]-i];
        }
        height = height * 256;
    }
    if (byte1[0] >= 0)
    {
        height = height + byte1[0];
    } else {
        height = height + 256 + byte1[0];
    }
    return height;
}


- (int)hextoint:(NSString *)string
{
    NSString *str1 = [NSString stringWithFormat:@"%lu",strtoul([[string substringToIndex:2] UTF8String],0,16)];
    NSString *str2 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(2, 2)] UTF8String],0,16)];
    NSString *str3 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(4, 2)] UTF8String],0,16)];
    NSString *str4 = [NSString stringWithFormat:@"%lu",strtoul([[string substringWithRange:NSMakeRange(6, 2)] UTF8String],0,16)];
    
    int  temp1 = [str1 intValue];
    int  temp2 = [str2 intValue];
    int  temp3 = [str3 intValue];
    int  temp4 = [str4 intValue];
    Byte dataVal[] = {temp1,temp2,temp3,temp4};
    int reVal = -1;
    
    
    reVal = (int)dataVal[3] << 24;
    
    reVal += (int)dataVal[2] << 16;
    
    reVal += (int)dataVal[1] << 8;
    
    reVal += (int)dataVal[0];
    return reVal;
}

//普通字符串转换为十六进制的。
- (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}





//测试
- (NSMutableArray *)hexToByteArr:(NSString *)str{
    int hexlen = (int)str.length;
    NSMutableArray *array = [NSMutableArray new];
    Byte result[str.length/2];
    if ([self isOdd:hexlen] == 1) {
        ++hexlen;
        str = [NSString stringWithFormat:@"0%@",str];
    }else{
        
    }
    
    int j = 0;
    for (int i = 0; i<hexlen; i+=2) {
        NSString *bstr = [NSString stringWithFormat:@"%lu",strtoul([[str substringWithRange:NSMakeRange(i, 2)] UTF8String],0,16)];
        if ([bstr intValue] >128) {
            bstr = [NSString stringWithFormat:@"%d",[bstr intValue]-256];
        }else if ([bstr intValue]<-128){
            bstr = [NSString stringWithFormat:@"%d",256+[bstr intValue]];
        }
        [array addObject:bstr];
        j++;
    }
    //    NSLog(@"%@",array);
    return array;
}

- (NSString *)getAddtion:(NSMutableArray *)byte{
    int len = byte.count;
    int num = 0;
    for (int i = 0; i<len; i++) {
        num += [byte[i] intValue];
        NSLog(@"基数：%@",[NSString stringWithFormat:@"%d",[byte[i] intValue]]);
        if (num>128) {
            num = num-256;
        }else if (num<-128){
            num = 256+num;
        }
        NSLog(@"求和：%@",[NSString stringWithFormat:@"%d",num]);
    }
    
    if (num<10 && num>0) {
        NSLog(@"--%@",[NSString stringWithFormat:@"0%@",[self ToHex:[[NSString stringWithFormat:@"0%d",num] intValue]]]);
        return [NSString stringWithFormat:@"0%@",[self ToHex:[[NSString stringWithFormat:@"0%d",num] intValue]]];
    }else if (num<0){
        num = 0-num;
        NSLog(@"==%@",[self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]]);
        return [self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]];
    }else{
        NSLog(@"++%@",[self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]]);
        return [self ToHex:[[NSString stringWithFormat:@"%d",num] intValue]];
    }
}

- (int)isOdd:(int )num{
    return num & 1;
}


-(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    return str;
}


//判断数字是否小于10 如果小于前面补0
- (NSString *)inFrontOfTheFill:(NSString *)str{
    if (str.length == 1) {
        str = [NSString stringWithFormat:@"0%@",str];
    }
    return str;
}
@end
